import React, { PureComponent } from 'react';
import styles from './datePicker.less';
import { formatDate } from '@/utils'
import DateModal from '@/components/dateModal'

import PropTypes from 'prop-types'

const time_arr = [
  { name: '今天' },
  { name: '本月' },
  { name: '本年' },
  { name: '其他时间' },
]

export default class DatePicker extends React.PureComponent {

  constructor(props){
    super(props);
    this.state = { 
      active: 0 
    }
  }

  componentDidMount(){
    // 如果有默认的时间
    if(this.props.defaultTime){
      const { beginDate, endDate } = this.props.defaultTime;
      const now = new Date();
      var active = 0;
      if(beginDate==endDate){ //当时间相同只有今天和其他时间两种
        if(beginDate!==formatDate(new Date())){ //当时间不等于今天那么active为3
          active = 3;
        }
      }else{
        if(beginDate.split('-')[1]==beginDate.split('-')[1]){ //当月份相等那么是本月的数据
          active = 1;
        } else {
          active = 2 //或者月份是年
        }
      }
      this.setState({ active })
    }
  }

  changeTab = (index) => {
    this.setState({ active: index }, ()=>{
      var params = {}
      switch (index) {
        case 0:
          params = {
            beginDate: formatDate(new Date()),
            endDate: formatDate(new Date())
          }
          this.props.handleChangeTab(params)
          break;
        case 1:
          var nowtime = new Date();
          var time = `${nowtime.getFullYear()}-${(nowtime.getMonth()+1<10) && '0'}${nowtime.getMonth()+1}`
          params= {
            beginDate: `${time}-01`,
            endDate: `${time}-31`
          }
          this.props.handleChangeTab(params)
          break;
        case 2:
          var nowtime = new Date();
          var time = `${nowtime.getFullYear()}`;
          params = {
            beginDate: `${time}-01-01`,
            endDate: `${time}-12-31`
          }
          this.props.handleChangeTab(params)
          break;
        case 3: 
          this.dateModal.show(this.props.equipCode);
          break;
        default:
          break;
      }
      
    })
  }

  // 选择其他时间
  chooseOtherDate = (date) => {
    this.props.handleChangeTab(date)
    this.dateModal.dismiss()
  }

  // 返回当前选中的日期范围是日、月或者年
  getActive = () => {
    // 如果选择是其他时间
    if(this.state.active==3){
      return this.dateModal.getType() // 0: 日 1: 月 2: 年
    }
    return this.state.active
  }

  render(){
    const { active } = this.state;
    return (
      [<div key="d" className={styles.time}>
        {time_arr.map((data,index)=>(
          <div key={data.name} onClick={()=>{ this.changeTab(index) }} className={`${styles.time_item}  ${active==index ? styles.time_tiem__active : ''}`}>
            {data.name}
          </div>
        ))}
      </div>,
      <DateModal submit={this.chooseOtherDate} key="m" ref={ el => { this.dateModal = el }} />]
    )
  }

}